<?php
namespace app\admin\controller; //命名空间，也说明了文件所在的文件夹
use Db;
use Request;
use think\Controller;

class Base extends Controller
{

    public function initialize()
    {
        //echo  \Request::module();
        $this->restLogin();
        $userid = session('userid');
        //$partitionid = session('partitionid');
        define('UID', $userid); //设置登陆用户ID常量

        define('MODULE_NAME', Request::module());
        define('CONTROLLER_NAME', Request::controller());
        define('ACTION_NAME', Request::action());

        //无需验证的操作
        $uneed_check      = array('login', 'logout', 'cleancache', 'vertify', 'imageUp', 'upload', 'login_task');
        $uneed_check_cont = array('Index', 'Main');

        if (in_array(CONTROLLER_NAME, $uneed_check_cont) || UID == '1') {
            return true; //后台首页控制器无需验证,超级管理员无需验证
        } elseif ((strpos(ACTION_NAME, 'ajax') !== false) || in_array(ACTION_NAME, $uneed_check)) {
            return true; //所有ajax请求不需要验证权限
        } else {
            $auth = new \my\Auth();
            if (!$auth->check(CONTROLLER_NAME . '/' . ACTION_NAME, UID)) {
                //$url = url('Login/auth', 'c=' . CONTROLLER_NAME . '&a=' . ACTION_NAME . '');
                if (!$this->request->isAjax()) {
                    //return $this->redirect($url); //redirect里面自带了url处理
                    return $this->redirect('Login/auth', ['c' => CONTROLLER_NAME, 'a' => ACTION_NAME]);
                } else {
                    $this->error('您没有权限访问', url('Login/auth', ['c' => CONTROLLER_NAME, 'a' => ACTION_NAME]));
                    //return abort(403, '访问被拒绝');
                }
                exit;
            }
        }

        
    }

    private function restLogin()
    {
        $userid = session('userid');
        if (empty($userid)) {
            //未登录
            $this->redirect('Login/loginOut');
        }
        //$config = new Config();
        $login_time = Db::name('webconfig')->where(['varname' => 'login_time'])->value('value');
        $now_token  = session('user_token'); //当前token

        $db_token = Db::name('token_user')->where(['uid' => $userid, 'type' => '1'])->find(); //数据库token
        if ($db_token['token'] != $now_token) {
            //其他地方登录
            $this->redirect('Login/loginOut');
        } else {
            if ($db_token['token_time'] < time()) {
                //登录超时
                //$this->error('错误', url('Login/index'));
                $this->redirect('Login/loginOut');
                exit;
            } else {
                $token_time = time() + $login_time;
                $data       = ['token_time' => $token_time];
                Db::name('token_user')->where(['uid' => $userid, 'type' => '1'])->update($data);
            }
        }
        return;
    }

}
